#!/usr/bin/python
# encoding=utf-8
'''
pip install PyMySQL

https://pymysql.readthedocs.io/en/latest/
'''
import time
import pymysql
import random

connection = pymysql.connect(host='localhost',
                             user='root',
                             password='abcd4321',
                             db='my-all-in',
                             charset='utf8mb4',
                             autocommit=True)


def new_register(promotionCode, cursor):
    print(promotionCode, 'new register task')
    if promotionCode == None or promotionCode == '':
        return cursor.execute('''
            insert into t_job_task(type, biz, status, done)
            values('STL_NEW_REGISTER', '{}', 'NEW', 0)
        ''')
    else:
        return cursor.execute('''
            insert into t_job_task(type, biz, status, done)
            values('STL_NEW_REGISTER', %s, 'NEW', 0)
        ''', ('{"promotionCode":"' + promotionCode + '"}'))

try:
    with connection.cursor() as cursor:
        while True:
            cursor.execute('''
                select count(1) from t_job_task where type = 'STL_NEW_REGISTER' and status in ('ING', 'NEW')
            ''')
            qty1 = cursor.fetchone()[0]
            print('qty1: ' + str(qty1))
            cursor.execute('''
                select count(1) from t_stl_account where idStatus is null
            ''')
            qty2 = cursor.fetchone()[0]
            print('qty2: ' + str(qty2))
            if qty1 == 0 and qty2 <= 2:
                if int(random.random() * 10000) <= 10:
                    new_register(None, cursor)
                else:
                    cursor.execute('''
                        select 
                            inviteCode 
                        from t_stl_account 
                        where 
                            idStatus = 'success'
                        and inviteCode is not null
                        and insertTime < date(now())
                        order by rand() limit 1
                    ''')
                    promotionCode = cursor.fetchone()[0]
                    new_register(promotionCode, cursor)
            connection.commit()
            time.sleep(1)
finally:
    connection.close()
